package com.yh.mybatis.datasource.pooled;

import java.util.ArrayList;
import java.util.List;

/**
 * 池状态
 *
 * @author yh
 * @date 2023/09/21
 */
public class PoolState {

    protected PooledDataSource dataSource;
    // 空闲连接
    protected final List<PooledConnection> idleConnections = new ArrayList<>();
    // 活跃连接
    protected final List<PooledConnection> activeConnections = new ArrayList<>();
    // 请求次数
    protected long requestCount = 0;
    // 总请求时间
    protected long accumulatedRequestTime = 0;
    protected long accumulatedCheckoutTime = 0;
    protected long claimedOverdueConnectionCount = 0;
    protected long accumulatedCheckoutTimeOfOverdueConnections = 0;

    //总等待时间
    protected long accumulatedWaitTime = 0;

    //要等待的次数
    protected long hadToWaitCount = 0;

    //失败连接次数
    protected long badConnectionCount = 0;

    public PoolState(PooledDataSource pooledDataSource) {
        this.dataSource = pooledDataSource;
    }

    /**
     * 获取请求计数
     *
     * @return long
     */
    public synchronized long getRequestCount() {
        return requestCount;
    }

    /**
     * 获取平均请求时间
     *
     * @return long
     */
    public synchronized long getAverageRequestTime() {
        return requestCount == 0 ? 0 : accumulatedRequestTime / requestCount;
    }

    /**
     * 获取平均等待时间
     *
     * @return long
     */
    public synchronized long getAverageWaitTime() {
        return hadToWaitCount == 0 ? 0 : accumulatedWaitTime / requestCount;
    }

    /**
     * 获取等待次数
     *
     * @return long
     */
    public synchronized long getHadToWaitCount() {
        return hadToWaitCount;
    }

    /**
     * 获取失败连接计数
     *
     * @return long
     */
    public synchronized long getBadConnectionCount() {
        return badConnectionCount;
    }

    /**
     * 获取过期的已声明连接总数
     *
     * @return long
     */
    public synchronized long getClaimedOverdueConnectionCount() {
        return claimedOverdueConnectionCount;
    }

    /**
     * 获取平均逾期结账时间
     *
     * @return long
     */
    public synchronized long getAverageOverdueCheckoutTime() {
        return claimedOverdueConnectionCount == 0 ? 0 : accumulatedCheckoutTimeOfOverdueConnections / claimedOverdueConnectionCount;
    }

    /**
     * 获取空闲连接数
     *
     * @return int
     */
    public synchronized int getIdleConnectionCount() {
        return idleConnections.size();
    }

    /**
     * 获取活动连接计数
     *
     * @return int
     */
    public synchronized int getActiveConnectionCount() {
        return activeConnections.size();
    }
}
